/****
Accenture IDC
Author - Sapna Jaamdar
v1.0

Revisions:
Bhumika Udani      v1.2             dt:21 February 2011         added try catch block in execute & finish method 
Bhumika Udani      v1.3             dt:15 March 2011            Introduced condition to move Leads with no appts in next 30 days to sharkpool.
Bhumika Udani      v1.4             dt:23 March 2011            Corrected the sharkpool assignment condition     
Manish Tiwari      v1.5             dt:18 August 2011           Corrected the sharkpool assignment condition and added new Conditions for more offices.
Bibhudutta Mishra  v1.6             dt:19 August 2011           Added new Conditions for more offices
Bhumika Udani      v1.7             dt:6th March 2012           Updated to include CHA and HEN office codes
Bhumika Udani      v2.0             dt:6th March 2012           Improved code for readability
Bhumika Udani      v3.0             dt:9th March 2012           OOR Telesales requirement # 1170, 1262, 
Bhumika Udani      v3.1             dt:17th April 2012          Updated test coverage
Bhumika Udani      v3.2             dt:9th May 2012 			Removed Days Assigned check
*/
global class SharkpoolOwnerReassignment implements Database.Batchable<sObject>{
     public   String query;
     public   Set<Id> QueueSet{get;set;}  
     public   String email;
     public   Id toSaltLakeQueueId;
     public   Id toNewJerseyQueueId;
     public   Id toAllentownQueueId;
     public   Id toBaltimoreQueueId;
     public   Id toBostonQueueId;
     public   Id toDenverQueueId;
     public   Id toHarrisburgQueueId;
     public   Id toLasVegasQueueId;
     public   Id toLongIslandQueueId;
     public   Id toMinneapolisQueueId;
     public   Id toNewYorkQueueId;
     public   Id toOaktonQueueId;
     public   Id toPhiladelphiaQueueId;
     public   Id toPhoenixQueueId;
     public   Id toPittsburghQueueId;
     public   Id toPortlandQueueId;
     public   Id toProvidenceQueueId;
     public   Id toRichmondQueueId;
     public   Id toSeattleQueueId;
     public   Id toVirginiaQueueId;
     public   Id toWhitePlainsQueueId;
     public   Id toGeneralQueueId;
     public   Id toHendersonQueueId;
     public   Id toCharlotteQueueId;


     
     Date currentdate = System.today();
     datetime myDateTime = datetime.now();
     //datetime newDateTime = myDateTime.addDays(30);    
    
    global database.querylocator start(Database.BatchableContext BC){
        system.debug('Recieved query'+query);
        return Database.getQueryLocator(query);
        }
        
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        List<Lead> leadList = new List<Lead>();
        List<SharkpoolSetting__c> sharkpoolfetchedRecordsList = new list<SharkpoolSetting__c>();
 
        Map<id,string> ownerMap = new Map<id,string>();
        Map<id,string> officeCodeMap = new Map<id,string>();
        Map<string, SharkpoolSetting__c> sharkpoolMap = new map<string,SharkpoolSetting__c>();
        map<string, decimal> officeApptMap = new map<string, decimal>();

        List<event> officeEventList = new List<event>();
        List<event> leventList = new List<event>();
        
        set<id> ownerIdSet = new set<id>();
        set<id> LeadIdSet = new set<id>();
        set<id> eventIdSet = new set<id>();
        set<string> roleNameSet = New set<string>();
        set<string> officeCodeSet = new set<string>();
        
        integer numberDaysDue = 0;
        integer numberDaysDue1 = 0;
        integer numberDateAssigned=0;

        for(sObject s : scope){
            Lead leadSelected = (lead)s;
            ownerIdSet.add(leadSelected.ownerid);
            
            LeadIdSet.add(leadSelected.id);
            system.debug(leadSelected.id);
        } 
        system.debug('Lead Ids in scope'+LeadIdSet); 
        
        List<user> leadOwnerList = [select id, sfa_office__c,UserRoleId from user where id in :ownerIdSet];
        
            for(User leadUser: leadOwnerList){
                ownerMap.put(leadUser.id,leadUser.UserRoleId);
                officeCodeMap.put(leadUser.id,leadUser.sfa_office__c);
                officeCodeSet.add(leadUser.sfa_office__c);
                
        }
        system.debug('Office code Set' + officeCodeSet);       
        system.debug('Office Code Map' + officeCodeMap);
         
        sharkpoolfetchedRecordsList =[select Active__c, SharkpoolQueueName__c, EmailNotificationDays__c, LastWorkDays__c, NextAppointmentDays__c, OfficeCode__c, OfficeName__c from SharkpoolSetting__c where active__c = true and  OfficeCode__c in: officeCodeSet];
        
        system.debug('Fetched Record List' + sharkpoolfetchedRecordsList );
        
        if(sharkpoolfetchedRecordsList.size()>0){
            for(SharkpoolSetting__c sRecord :sharkpoolfetchedRecordsList){
              sharkpoolMap.put(sRecord.OfficeCode__c, sRecord);
             // officeApptMap.put(sRecord.OfficeCode__c,sRecord.NextAppointmentDays__c);
            }
            system.debug('To be used Sharkpool Map'  +sharkpoolMap);
        }

          
        
        //Select the event on leads with start date  >= today   
        officeEventList =[select whoid,SFA_Office_Code__c, StartDateTime from event  where whoid in: LeadIdSet and StartDateTime >=: myDateTime ];
        system.debug('Event under office' + officeEventList );
        
        //Further select only those events which are falling before the next appointment days of corresponding office       
        if(officeEventList.size()>0){        
          for(Event evt :officeEventList){
                integer apptDays = integer.valueof(sharkpoolMap.get(evt.SFA_Office_Code__c).NextAppointmentDays__c - sharkpoolMap.get(evt.SFA_Office_Code__c).EmailNotificationDays__c );
                system.debug('Appointment Days '+apptDays);
                system.debug('Event Start time' + evt.StartDateTime);
                  if(evt.StartDateTime <= myDateTime.addDays(apptDays)) {
                        leventList.add(evt);
                 }         
          }
          system.debug(leventList);
        }
        
        if(leventList.size()>0){
           for(event leadEvent:leventList){
                  eventIdSet.add(leadEvent.whoid); 
           }
           system.debug('Event Ids' +eventIdSet);
        }     
        
                
        
        for(sObject s : scope){
        
            Lead leadToUpdate = new Lead();
            leadToUpdate = (Lead)s;     
        
            if(leadToUpdate.Last_Worked__c != null && leadToUpdate.Date_Assigned__c!=null ){
            
                    date myLastWorkedDate = date.newinstance(leadToUpdate.last_worked__C.year(), leadToUpdate.last_worked__C.month(), leadToUpdate.last_worked__C.day());
                    numberDaysDue = myLastWorkedDate.daysBetween(currentdate);
                
                    date myLastDateAssigned = date.newinstance(leadToUpdate.Date_Assigned__c.year(), leadToUpdate.Date_Assigned__c.month(), leadToUpdate.Date_Assigned__c.day());
                    numberDateAssigned= myLastDateAssigned.daysBetween(currentdate);
         
            }
            
            date myCreatedDate = date.newinstance(leadToUpdate.CreatedDate.year(), leadToUpdate.CreatedDate.month(), leadToUpdate.CreatedDate.day());
            numberDaysDue1 = myCreatedDate.daysBetween(currentdate);
            
            if(leadToUpdate.User_Office_Code__c!= null){
            system.debug('SHarkpoooooool'+sharkpoolMap.get(leadToUpdate.User_Office_Code__c).LastWorkDays__c);
            }
            if(sharkpoolMap.containsKey(leadToUpdate.User_Office_Code__c)){
                integer diffLastWorkEmailNotificationDays  = integer.valueOf(sharkpoolMap.get(leadToUpdate.User_Office_Code__c).LastWorkDays__c - sharkpoolMap.get(leadToUpdate.User_Office_Code__c).EmailNotificationDays__c);
            
            //Check for sending email notification emails
            // Removed condition check for Days Assigned
                    if(leadToUpdate.Days_Untouched__c == diffLastWorkEmailNotificationDays ) {  
        
                        system.debug('Inside recieving email');
                            try{
                                set<id> leadMailIdSet = new set<id>();
                                leadMailIdSet.add(leadToUpdate.id); 
            
                                Messaging.SingleEmailMessage singleMailObj = new Messaging.SingleEmailMessage();
    
                                singleMailObj.setToAddresses(new String[] {leadToUpdate.owner.EMAIL});
                                singleMailObj.setSenderDisplayName('Markets Group');
                                singleMailObj.setSubject('Shark Pool Assignment Update');
                                singleMailObj.setHtmlBody('Dear Media Consultant,<br/><br/><p>The following lead will be released to the Shark Pool if you do not contact this customer within the ' +sharkpoolMap.get(leadToUpdate.User_Office_Code__c).EmailNotificationDays__c + 'days. Please make every effort to contact this potential customer ASAP.</p><br/>Lead Name: ' + leadToUpdate.Name + '<br/> Phone:'
                                     + leadToUpdate.Phone + '<br/> Lead Company Name:' + leadToUpdate.Company + '<br/> Lead Status:' + leadToUpdate.Status + '<br/> Lead Source:'+ leadToUpdate.LeadSource);            
                                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { singleMailObj });
                                }
                           catch(exception emailException){
                                system.debug('Exception for sending email :' + emailException); }

                    }
    
         //Check for moving the lead to Sharkpool queue, removed days assigned condition check -> :numberDateAssigned >= integer.valueOf(sharkpoolMap.get(leadToUpdate.User_Office_Code__c).DaysLastAssigned__c)     
                 if( leadToUpdate.Days_Untouched__c >= integer.valueOf(sharkpoolMap.get(leadToUpdate.User_Office_Code__c).LastWorkDays__c) ){
                     system.debug('other condition ' + integer.valueOf(sharkpoolMap.get(leadToUpdate.User_Office_Code__c).LastWorkDays__c));

                         system.debug('I am inside 14 day condition '+ leadToUpdate.id);
                 
                     if(!(eventIdSet.contains(leadToUpdate.id))){
                         system.debug('This even is present '+leadToUpdate.id);
                             string roleNameString;
                     
                         UserRole ownerRoleName =[Select Name from UserRole where Id=:ownerMap.get(leadToUpdate.ownerId) Limit 1];
                         system.debug('ownerRoleName '+ ownerRoleName );        
                         roleNameString = ownerRoleName.Name;
             
                         system.debug('roleNameString '+roleNameString );
                     
                         /** for(UserRole roleNameToAdd :ownerRoleName){
                          roleNameSet.add(roleNameToAdd.Name);
                             }
                             **/
                     
                         //system.debug('ROLE NAMES'+rolename);
                         //if(ownerMap.get(leadToUpdate.ownerId) == 'Salt Lake City') 
                     
                      if(roleNameString.contains('OOR Salt Lake City')|| roleNameString.contains('OOR SL')||roleNameString.contains('OOR SLC')){
                             leadToUpdate.ownerid = toSaltLakeQueueId;
                             leadList.add(leadToUpdate);
                         }

                     else if(roleNameString.contains('OOR New Jersey')|| roleNameString.contains('OOR NJ')){ 
                             leadToUpdate.ownerid = toNewJerseyQueueId;
                             leadList.add(leadToUpdate);
                         }
                     
                     else if(roleNameString.contains('OOR Allentown')){ 
                             leadToUpdate.ownerid = toAllentownQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Baltimore')){ 
                             leadToUpdate.ownerid = toBaltimoreQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Boston')||roleNameString.contains('OOR SFA Boston')){ 
                             leadToUpdate.ownerid = toBostonQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Charlotte')){
                             leadToUpdate.ownerid = toCharlotteQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Denver')){ 
                             leadToUpdate.ownerid = toDenverQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Harrisburg')){ 
                             leadToUpdate.ownerid = toHarrisburgQueueId;
                             leadList.add(leadToUpdate);                         
                         }
                     else if(roleNameString.contains('OOR Henderson')){
                             leadToUpdate.ownerid = toHendersonQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Las Vegas')){ 
                             leadToUpdate.ownerid = toLasVegasQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Long Island')){ 
                             leadToUpdate.ownerid = toLongIslandQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Minneapolis')){ 
                             leadToUpdate.ownerid = toMinneapolisQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR New York')){ 
                             leadToUpdate.ownerid = toNewYorkQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Oakton')){ 
                             leadToUpdate.ownerid = toOaktonQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Philadelphia')){ 
                             leadToUpdate.ownerid = toPhiladelphiaQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Phoenix')){ 
                             leadToUpdate.ownerid = toPhoenixQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Pittsburgh')){ 
                             leadToUpdate.ownerid = toPittsburghQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Portland')){ 
                             leadToUpdate.ownerid = toPortlandQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Providence')){ 
                             leadToUpdate.ownerid = toProvidenceQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Richmond')){ 
                             leadToUpdate.ownerid = toRichmondQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Seattle')){ 
                             leadToUpdate.ownerid = toSeattleQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR Virginia Beach')){ 
                             leadToUpdate.ownerid = toVirginiaQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else if(roleNameString.contains('OOR White Plains')){ 
                             leadToUpdate.ownerid = toWhitePlainsQueueId;
                             leadList.add(leadToUpdate);
                         }
                     else{
                             leadToUpdate.ownerid = toGeneralQueueId;
                             leadList.add(leadToUpdate);
                         }
                     }
                 }
            
    update leadList ;
    //leadList.clear();
             } // Sharkpool Map check condition ends
            system.debug('This lead wasnt updated' +leadToUpdate);
        }
    
     }
    
    global void finish(Database.BatchableContext BC){
        try{
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        //email=[select email from User where id=:UserInfo.getUserId() limit 1].email;
        mail.setToAddresses(new String[] {'sfdc-noreply@attinteractive.com'});
        mail.setReplyTo('batch@acme.com');
        mail.setSenderDisplayName('Batch Processing');
        mail.setSubject('Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        } catch (exception finishexception){
            system.debug('Exception in finish method: '+finishexception);
            }
    }
    
    
/* test class for classes/triggers */
  static testMethod void SharkpoolOwnerReassignment() {
   
   Map<integer,string> city = new Map<integer,string>{0=>'OOR White Plains',1=>'OOR SLC',2=>'OOR NJ',3=>'OOR Allentown',4=>'OOR Baltimore',5=>'OOR Boston',6=>'OOR Charlotte',7=>'OOR Denver',8=>'OOR Harrisburg',9=>'OOR Henderson',10=>'OOR Las Vegas',11=>'OOR Long Island',12=>'OOR Minneapolis',13=>'OOR New York',14=>'OOR Oakton',15=>'OOR Philadelphia',16=>'OOR Phoenix',17=>'OOR Pittsburgh',18=>'OOR Portland',19=>'OOR Providence',20=>'OOR Richmond',21=>'OOR Seattle',22=>'OOR Virginia Beach'};  
   Map<integer, string> scity = new map<integer, string>{0=>'WPN',1=>'SLC',2=>'NNJ',3 => 'NEP',4 => 'BLT',5=> 'BOS',6=> 'CHA',7=>'DEN',8=>'HPA',9=>'HEN',10=> 'LVN',11 => 'LIN',12 =>'MIN',13=> 'NYC',14=>'NVA',15 =>'PHI',16=>'PHX',17=>'PIT',18=>'POR',19 =>'PRI',20=>'RVA',21=>'SWA',22=>'VVA'};
   Map<string,id> QueryMap = new Map<string,id>();

   List<QueueSobject> OORQuerylist = [Select QueueId,queue.name from QueueSobject q where sobjecttype ='Lead'];
   List<UserRole> RoleList = new List<UserRole>();
   List<User> UserList = new List<User>();
   List <Lead> leadlist = new List<Lead>();
   List <event> eventList = new List<event>();
   
   Set<Id> queueId= New Set<Id>();
   
   date myDate = date.today();

       for(QueueSobject QS:OORQuerylist){        
                QueryMap.put(QS.queue.name,QS.QueueId); 
                queueId.add(QS.QueueId);      
            }
            
        //User owners = [select id, sfa_office__c from user where sfa_office__c = 'Salt Lake City' and isActive = true limit 1];
 
 profile profid = [Select Id from profile q where profile.Name ='SFA OOR Media Consultants'];
 
  
 id masterrole  = [select id from userRole where name =:'Information Systems'].id;
 
 //system.debug('@@@@@'+masterrole);
 
  for(integer i=1;i<23;i++){
      UserRole singlerole = new UserRole();
             singlerole.Name = city.get(i);
             singlerole.ParentRoleId=masterrole;
     RoleList.add(singlerole);
  }
  
  insert RoleList;
  
        
  //system.debug('Profiles'+RoleList);
 //UserRole aas_role = [select id from UserRole where userRole.Name = 'AAS Collections '];
    for(integer i=0;i<RoleList.size();i++){
        User nuser = new User();
        nuser.UserName = 'aasTestUser@atti-temp'+i+'.com';
        nuser.LastName = 'aasTest NJ'+city.get(i);
        system.debug('UUUUU'+nuser.LastName);
        nuser.Email = 'a_test@atti.com';
        nuser.Alias = 'Aas'+i;
        nuser.CommunityNickname = 'aasTest'+i;
        nuser.TimeZoneSidKey = 'America/Los_Angeles'; 
        nuser.LocaleSidKey = 'en_US';
        nuser.EmailEncodingKey = 'UTF-8'; 
        nuser.ProfileId = profid.id ; 
        nuser.UserRoleId = RoleList[i].id;
        nuser.LanguageLocaleKey = 'en_US';
        //string uo = city.getMap(i);
        nuser.sfa_office__c = scity.get(i);
        system.debug('nuser.sfa_office__c ++' +nuser.sfa_office__c);
        nuser.Isactive =true;
        UserList.add(nuser);
    }
        insert UserList;
        system.debug('UUUUU'+UserList);

        User ThisUser = [select id from user where profile.name = 'System Administrator' AND ISACTIVE = TRUE limit 1];
        
        system.runas(ThisUser){
                   
       for(integer i = 0; i<29; i++){
            Lead a = new Lead(lastname='testLead'+i,company='testLead'+i,LeadSource='Internet');
            if(i>0 && i<10)
                a.Last_Worked__c = DateTime.now()-7;
                a.Date_Assigned__c = myDate.addDays(-7);

               // a.ownerid = UserList[i].id;
            if(i>10 && i<17){                
                a.Last_Worked__c = DateTime.now()- i;
                a.Date_Assigned__c = myDate.addDays(-i);


                //a.ownerid = UserList[i].id;

                //a.ownerId = nuser.Id;
            }
            if(i>17 && i<22){
            a.Last_Worked__c = DateTime.now()- 15;
            a.Date_Assigned__c = myDate.addDays(-15);
            
            }
            leadlist.add(a);
            
        }
        insert leadlist;
        system.debug('LLL'+leadlist);
        for(integer userIterator=0;userIterator<UserList.size();userIterator++){
                leadlist[userIterator].User_Office_Code__c = UserList[userIterator].sfa_office__c;
                leadlist[userIterator].ownerid = UserList[userIterator].id; 
                
                event eventTest = new event();
                eventTest.whoid = leadlist[userIterator].id;
                eventTest.subject = 'Sharkpool test check';
                eventTest.ownerid = UserList[userIterator].id;
                eventTest.StartDateTime = DateTime.now()+ 30;
                eventTest.EndDateTime = DateTime.now()+ 35;
                eventTest.Appointment_Type__c = 'Other';
                eventTest.SFA_Office_Code__c = UserList[userIterator].sfa_office__c;

                
                eventList.add(eventTest);
                
        }
        insert eventList;
        update leadlist;
        system.debug('userIterator' + leadlist);
        }
        
        Test.startTest();
        SharkpoolOwnerReassignment job = new SharkpoolOwnerReassignment();
        job.QueueSet = queueId;
        
        job.query = 'Select Id, Name,phone, company,status,Date_Assigned__c,User_Office_Code__c, Days_Untouched__c, LeadSource,createddate,Last_Worked__C, Ownerid,Owner.Email From Lead where name Like \'testLead%\' Limit 10';

        job.toSaltLakeQueueId=QueryMap.get('Sharkpool - Salt Lake (SLC)');     
        job.toNewJerseyQueueId=QueryMap.get('Sharkpool - New Jersey (NNJ)');     
        job.toAllentownQueueId=QueryMap.get('Sharkpool - Allentown (NEP)');     
        job.toBaltimoreQueueId=QueryMap.get('Sharkpool - Baltimore (BLT)');    
        job.toBostonQueueId=QueryMap.get('Sharkpool - Boston (BOS)');     
        job.toDenverQueueId=QueryMap.get('Sharkpool - Denver (DEN)');     
        job.toHarrisburgQueueId=QueryMap.get('Sharkpool - Harrisburg (HPA)');     
        job.toLasVegasQueueId=QueryMap.get('Sharkpool - Las Vegas (LVN)');     
        job.toLongIslandQueueId=QueryMap.get('Sharkpool - Long Island (LIN)');     
        job.toMinneapolisQueueId=QueryMap.get('Sharkpool - Minneapolis (MIN)');     
        job.toNewYorkQueueId=QueryMap.get('Sharkpool - New York (NYC)');     
        job.toOaktonQueueId= QueryMap.get('Sharkpool - Oakton (NVA)');    
        job.toPhiladelphiaQueueId = QueryMap.get('Sharkpool - Philadelphia (PHI)');     
        job.toPhoenixQueueId = QueryMap.get('Sharkpool - Phoenix (PHX)');     
        job.toPittsburghQueueId = QueryMap.get('Sharkpool - Pittsburgh (PIT)');     
        job.toPortlandQueueId = QueryMap.get('Sharkpool - Portland (POR)');     
        job.toProvidenceQueueId = QueryMap.get('Sharkpool - Providence (PRI)');     
        job.toRichmondQueueId = QueryMap.get('Sharkpool - Richmond (RVA)');     
        job.toSeattleQueueId = QueryMap.get('Sharkpool - Seattle (SWA)');     
        job.toVirginiaQueueId = QueryMap.get('Sharkpool - Virginia Beach (VVA)');    
        job.toWhitePlainsQueueId = QueryMap.get('Sharkpool - White Plains (WPN)');    
        job.toGeneralQueueId = QueryMap.get('SFA OOR General Sharkpool Queue'); 
        job.toCharlotteQueueId = QueryMap.get('Sharkpool - Charlotte (CHA)');
        job.toCharlotteQueueId = QueryMap.get('Sharkpool - Henderson(HEN)');

        ID batchprssid = Database.executeBatch(job, 10);
        Test.stopTest();
        
        AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id = :batchprssid ];
        System.debug('\n\nFinal results are: '+a);
        System.AssertEquals('Completed', a.status);
        //System.AssertEquals(0, a.NumberOfErrors);
  }    
}